package com.geoai.uimap.core.mapbox

import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.mapboxsdk.plugins.annotation.*
import com.mapbox.mapboxsdk.utils.ColorUtils
import com.geoai.uimap.api.IGEOMap
import com.geoai.uimap.api.GEOMapPolygon
import com.geoai.uimap.geo.ILatLng
import com.geoai.uimap.utils.getMapBoxGeometry

class MapboxPolygon(private val map: IGEOMap) : GEOMapPolygon() {

    //闭合的要素
    private var mFill: Fill? = null

    //Polygon的边界
    private var mLine: Line? = null

    private var lineManager: LineManager? = null
    private var fillManager: FillManager? = null

    override fun show(): GEOMapPolygon {
        if (mPointList.isNullOrEmpty()) return this
        val mapBoxManager = map.getMapBoxGeometry() ?: return this
        val fillManager = mapBoxManager.getFillManager()
        this.fillManager = fillManager
        val lineManager = mapBoxManager.getLineManager()
        this.lineManager = lineManager
        if (fillManager == null) {
            return this
        }
        val innerLatLngs: MutableList<LatLng> = ArrayList()
        mPointList?.forEach {
            innerLatLngs.add(LatLng(it.latitude, it.longitude))
        }
        innerLatLngs.add(LatLng(mPointList!![0].latitude, mPointList!![0].longitude))
        val latLngs: MutableList<List<LatLng>> = ArrayList()
        latLngs.add(innerLatLngs)
        val fillOptions = FillOptions()
                .withLatLngs(latLngs)
                .withFillColor(ColorUtils.colorToRgbaString(mFillColor))
                .withFillOutlineColor(ColorUtils.colorToRgbaString(mStrokeColor))
        mFill = fillManager.create(fillOptions)

        lineManager?.let {
            val lineOptions = LineOptions()
                    .withLatLngs(innerLatLngs)
                    .withLineColor(ColorUtils.colorToRgbaString(mStrokeColor))
                    .withLineWidth(mStrokeWidth)
            mLine = lineManager.create(lineOptions)
        }

        return this
    }

    override fun setPositions(positions: List<ILatLng>): GEOMapPolygon {
        mPointList = positions
        val innerLatLngs: MutableList<LatLng> = ArrayList()
        mPointList?.forEach {
            innerLatLngs.add(LatLng(it.latitude, it.longitude))
        }
        innerLatLngs.add(LatLng(mPointList!![0].latitude, mPointList!![0].longitude))
        val latLngs: MutableList<List<LatLng>> = ArrayList()
        latLngs.add(innerLatLngs)
        mFill?.latLngs = latLngs
        fillManager?.updateSource()

        mLine?.latLngs = innerLatLngs
        lineManager?.updateSource()
        return super.setPositions(positions)
    }

    override fun destroy() {
        mFill?.let {
            map.getMapBoxGeometry()?.getFillManager()?.delete(it)
        }
        mLine?.let {
            map.getMapBoxGeometry()?.getLineManager()?.delete(it)
        }
    }
}